package middleware

import (
	"net/http"
	"strings"

	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware 认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			common.Error(c, http.StatusUnauthorized, "unauthorized", nil)
			c.Abort()
			return
		}

		// 检查token格式
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			common.Error(c, http.StatusUnauthorized, "invalid_auth_format", nil)
			c.Abort()
			return
		}

		// 验证token
		claims, err := auth.ValidateToken(parts[1])
		if err != nil {
			common.Error(c, http.StatusUnauthorized, "invalid_token", err)
			c.Abort()
			return
		}

		// 检查用户信息是否存在
		if claims.Username == "" {
			common.Error(c, http.StatusUnauthorized, "user_not_found", nil)
			c.Abort()
			return
		}

		// 检查用户是否已被删除
		if claims.IsDeleted {
			common.Error(c, http.StatusUnauthorized, "user_deleted", nil)
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("claims", claims)
		c.Set("user_id", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("role_id", claims.RoleID)

		c.Next()
	}
}
